package com.karrim.server.io;


import com.google.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashSet;
import java.util.logging.Level;
import java.util.logging.Logger;

public class InputReaderThread extends Thread {

    @Inject
    public InputReaderThread(LinkedHashSet<String> inputBuffer) {
        this(inputBuffer, false);
    }

    public InputReaderThread(LinkedHashSet<String> inputBuffer, boolean autoStart) {
        super("InputReaderThread");

        input = inputBuffer;

        if (autoStart) {
            start();
        }
    }

    @Override
    public void interrupt() {
        super.interrupt();
        interrupted = true;
    }

    @Override
    synchronized public void run() {
        try {
            char[] block;
            StringBuffer sb = new StringBuffer();
            while (!interrupted) {
                int pos;
                if ((pos = sb.toString().indexOf(Parser.DEFAULT_DELIMITER)) != -1) {
                    input.add(sb.substring(0, pos));
                    sb = new StringBuffer(sb.substring(pos + 1));
                } else {
                    if (DEFAULT_INPUT_STREAM.available() > 0) {
                        int available = DEFAULT_INPUT_STREAM.available();
                        while (READ_BLOCK_SIZE < available) {
                            block = new char[READ_BLOCK_SIZE];
                            in.read(block);
                            sb.append(block);
                        }
                        block = new char[available];
                        in.read(block);
                        sb.append(block);
                    } else {
                        try {
                            wait(DEFAULT_TIMEOUT);
                        } catch (InterruptedException ie) {
                            break;
                        }
                    }
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private LinkedHashSet<String> input;
    private boolean interrupted = false;
    public final InputStream DEFAULT_INPUT_STREAM = System.in;
    private InputStreamReader in = new InputStreamReader(DEFAULT_INPUT_STREAM);
    public final int READ_BLOCK_SIZE = 1000;
    private final long DEFAULT_TIMEOUT = 500;
}